//
//  StatusViewModel.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/19.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit

///微博视图模型 - 处理单条微博的业务逻辑
class StatusViewModel: CustomStringConvertible {

    /// 微博的模型
    var status: Status
    
    /// 表格的可重用表示符
    var cellId: String {
    
        return status.retweeted_status != nil ? StatusRetweetedCellId : StatusCellNormalId
    }
    
    /// 缓存的行高
    lazy var rowHeight: CGFloat = {
    
        var cell: StatusCell
        
        if self.status.retweeted_status != nil {
            cell = StatusRetweetedCell(style: .Default, reuseIdentifier: StatusRetweetedCellId)
        } else {
            cell = StatusNormalCell(style: .Default, reuseIdentifier: StatusCellNormalId)
        }
        
        // 2. 记录高度
        return cell.rowHeight(self)
        
       
}()
    /// 用户头像 URL
    var userProfileUrl: NSURL {
        return NSURL(string: status.user?.profile_image_url ?? "")!
    }
    
    /// 用户默认头像
    var userDefaultIconView: UIImage? {
        return UIImage(named: "avatar_default_big")
    }
    
    /// 用户会员图标
    var userMemberImage: UIImage? {
        
        // 庚呼 mbrank 来生成突图像
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
           return UIImage(named: "common_icon_membership_level\(status.user!.mbrank)")
        }
        return nil
    }
    
    /// 用户认证图标
    var userVipImage: UIImage? {
        switch(status.user?.verified_type ?? -1) {
        
        case 0: return UIImage(named: "avatar_vip")
        case 2, 3, 5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
        default: return nil
        }
    }
    
    /// 缩略图URL数组 - 存储型属性
    var thumbnailUrls: [NSURL]?
    
    var retweetedText: String? {
        
        // 1. 判断是否是转发微博，如果不是直接返回 nil
        guard let s = status.retweeted_status else {
            return nil
        }
        
        // 2. s 就是转发微博
        return "@" + (s.user?.screen_name ?? "") + ":" + (s.text ?? "")
    }
    
    /// 构造函数
    init(status:Status) {
        self.status = status
        
        //根据模型来生成缩略图数组
        if let urls = status.retweeted_status?.pic_urls ?? status.pic_urls{
        
            // 创建 URL 缩略图数组
            thumbnailUrls = [NSURL]()

            //遍历字典
            for dict in urls {
            
                guard let url = NSURL(string: dict["thumbnail_pic"]!) else {
                 
                    continue
            }
            thumbnailUrls?.append(url)
        }
    }
    }
    
    /// 描述信息
    var description: String {
    
        return status.description + "配图数组\(thumbnailUrls ?? [] as NSArray)"
    }
}